package com.ruoyi.framework.web.service.app;

import com.ruoyi.common.core.domain.entity.H5User;
import com.ruoyi.common.core.domain.model.H5RegisterBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.sms.SmsCodeService;
import com.ruoyi.framework.util.LoginCommonUtil;
import com.ruoyi.system.service.IH5UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class H5RegisterService {


    @Autowired
    private IH5UserService h5UserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private LoginCommonUtil loginCommonUtil;

    @Autowired
    private SmsCodeService smsCodeService;
    
    @Value("${aliyun.sms.enabled:false}")
    private boolean smsEnabled;
    
    @Value("${aliyun.sms.mock.enabled:false}")
    private boolean mockEnabled;

    /**
     * H5用户注册逻辑
     */
    @Transactional
    public void register(H5RegisterBody registerBody) {
        String username = registerBody.getUsername();
        String phone = registerBody.getPhonenumber();
        String password = registerBody.getPassword();
        String code = registerBody.getCode();
        String uid = registerBody.getUuid();

        // 1. 校验用户名/手机号是否已存在
        if (h5UserService.selectUserByUsername(username) != null) {
            throw new ServiceException("用户已存在");
        }
        if (h5UserService.selectUserByPhoneNumber(phone) != null) {
            throw new ServiceException("手机号已被注册");
        }

        // 2. 校验图形验证码
        loginCommonUtil.validateRegisterCaptcha(username, code, uid);

        // 3. 校验短信验证码（如果功能启用或模拟模式启用）
        if (smsEnabled || mockEnabled) {
            String smsCode = registerBody.getSmsCode();
            if (!smsCodeService.verifySmsCode(phone, smsCode, "register")) {
                throw new ServiceException("短信验证码错误或已过期");
            }
        } else {
            log.info("短信验证码功能已禁用，跳过短信验证码校验");
        }

        // 4. 构建H5用户实体
        H5User h5User = new H5User();
        h5User.setUserName(username);
        h5User.setNickName(registerBody.getNickName());
        h5User.setPhonenumber(phone);
        h5User.setPassword(bCryptPasswordEncoder.encode(password)); // 密码加密
        h5User.setUserType("10"); // 10=原生H5用户
        h5User.setStatus("0"); // 初始状态：未验证手机号（若已验证可设为0）
        h5User.setCreateBy("system");
        h5User.setCreateTime(DateUtils.getNowLocalDateTime());
        h5User.setRemark("H5注册用户");

        // 5. 保存用户信息
        if (h5UserService.insertH5User(h5User) <= 0) {
            throw new ServiceException("注册失败，服务器异常");
        }

        // 6. 异步记录注册日志
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, phone, IpUtils.getIpAddr()));
    }
}
